package com.lanxi.nbpaytest;

import java.util.HashMap;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
/**
 * RSA加密解密 不可继承
 * @author LIU
 * 2020-02-13
 */
public final class NbankRSAUtil {
	/**
	 * 单次最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;
	/**
	 * 单次最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;
	/**
	 * RSA编码
	 */
	private static final String CHARSET = "UTF-8";
	/**
	 * 生成公私密钥对
	 * @Description 生成公私密钥对
	 */
	public static Map<String, String> generateKey() throws Exception {
		try {
			KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
			kpg.initialize(1024);
			KeyPair kp = kpg.genKeyPair();
			PublicKey pbkey = kp.getPublic();
			PrivateKey prkey = kp.getPrivate();
			String publicKey = Base64.getEncoder().encodeToString(pbkey.getEncoded());
			String privateKey = Base64.getEncoder().encodeToString(prkey.getEncoded());
	        Map<String, String> keyPairMap = new HashMap<String, String>();
	        keyPairMap.put("publicKey", publicKey);
	        keyPairMap.put("privateKey", privateKey);
	        return keyPairMap;
		} catch (Exception e) {
			throw new Exception("生成公私密钥对失败!");
		}
	}

	/**
	 * 获取私钥
	 * @Description 将base64编码后的公钥字符串转成PublicKey实例
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(String publicKey) throws Exception {
		byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes(CHARSET));
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(keySpec);
	}

	/**
	 * 获取私钥
	 * 将base64编码后的私钥字符串转成PrivateKey实例
	 * @Description 将base64编码后的私钥字符串转成PrivateKey实例
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKey(String privateKey) throws Exception {
		byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes(CHARSET));
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePrivate(keySpec);
	}

	/**
	 * 公钥加密
	 * 
	 * @param content 加密原文
	 * @param publicKey 加密使用的公钥
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int inputLen = content.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(content, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(content, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	/**
	 * 公钥加密
	 * 
	 * @param content 加密内容原文
	 * @param publicKey 加密使用的公钥字符串
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String content, String publicKey) throws Exception {
		byte[] contentByte = content.getBytes(CHARSET);
		PublicKey pubKey = NbankRSAUtil.getPublicKey(publicKey);
		byte[] resultByte = NbankRSAUtil.encrypt(contentByte, pubKey);
		String resultStr = Base64.getEncoder().encodeToString(resultByte);
		return resultStr;
	}

	/**
	 * 私钥解密
	 * @Description 私钥解密
	 * @param content 需要解密的密文
	 * @param privateKey 解密使用的私钥
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception {

		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		int inputLen = content.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(content, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(content, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}

	/**
	 * 私钥解密
	 * @Description 私钥解密
	 * @param content 解密内容
	 * @param privateKey 解密私钥
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String content, String privateKey) throws Exception {
		// 获取私钥
		PrivateKey priKey = getPrivateKey(privateKey);
		byte[] encryptByte = Base64.getDecoder().decode(content);
		byte[] rawByte = NbankRSAUtil.decrypt(encryptByte, priKey);

		return new String(rawByte);
	}

	/**
	 * 私钥加签
	 * 
	 * @param content 原文
	 * @param privateKey 私钥
	 * @return 签名值
	 */
	public static String signByPrivateKey(String content, String privateKey) {
		try {
			PrivateKey priKey = NbankRSAUtil.getPrivateKey(privateKey);
			Signature signature = Signature.getInstance("SHA256withRSA");// MD5withRSA
			signature.initSign(priKey);
			signature.update(content.getBytes(CHARSET));
			byte[] sign = signature.sign();
			String signStr = Base64.getEncoder().encodeToString(sign);
			return signStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 公钥验签
	 * 
	 * @param content 原文
	 * @param publicKey 公钥
	 * @param sign 签名
	 * @return 验签是否通过
	 */
	public static boolean verifySignByPublicKey(String content, String publicKey, String sign) throws Exception {
		try {
			PublicKey pubKey = NbankRSAUtil.getPublicKey(publicKey);
			Signature signature = Signature.getInstance("SHA256withRSA");// MD5withRSA
			signature.initVerify(pubKey);
			signature.update(content.getBytes(CHARSET));
			return signature.verify(Base64.getDecoder().decode(sign));
		} catch (Exception e) {
			throw new Exception("验签失败!"+e);
		}
	}

}
